﻿
using AutoMapper;
using NFine.Util;
using NFine.Data.Dto.SystemManage;
using NFine.Data.Entity.SystemManage;
using NFine.Repository.SystemManage;
using SharpRepository.Repository.Queries;
using SharpRepository.Repository.Specifications;
using Snowflake;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NFine.Service.SystemManage
{
    public class RegionService
    {
        RegionRepository regionRepository = new RegionRepository(SharpRepoConfig.sharpRepoConfig, "efCore");

        public List<RegionGridDto> GetList()
        {
            long? tenantId = OperatorProvider.Provider.GetOperator().TenantModel.Id;
            var specification = new Specification<Region>();
            specification = new Specification<Region>(t => t.TenantId == tenantId);
            var sortingOtopns = new SortingOptions<Region, int?>(x => x.Id, isDescending: false);
            var list = regionRepository.FindAll(specification, sortingOtopns).ToList();
            return Mapper.Map<List<RegionGridDto>>(list);
        }

        public RegionOutputDto GetForm(string keyValue)
        {
            long? tenantId = OperatorProvider.Provider.GetOperator().TenantModel.Id;
            var id = Convert.ToInt32(keyValue);
            RegionOutputDto regionOutputDto = new RegionOutputDto();
            Region region = regionRepository.Find(t => t.TenantId == tenantId && t.Id == id);
            AutoMapper.Mapper.Map<Region, RegionOutputDto>(region, regionOutputDto);
            return regionOutputDto;
        }

        public void SubmitForm(RegionInputDto regionInputDto, string keyValue)
        {
            long? tenantId = OperatorProvider.Provider.GetOperator().TenantModel.Id;
            Region region = new Region();
            if (!string.IsNullOrEmpty(keyValue))
            {
                int id = Convert.ToInt32(keyValue);
                region = regionRepository.Find(t => t.TenantId == tenantId && t.Id == id);
                AutoMapper.Mapper.Map<RegionInputDto, Region>(regionInputDto, region);
                regionRepository.Update(region);
            }
            else
            {
                AutoMapper.Mapper.Map<RegionInputDto, Region>(regionInputDto, region);
                regionRepository.Add(region);
            }
        }

        public void DeleteForm(string keyValue)
        {
            int id = Convert.ToInt32(keyValue);
            Region region = regionRepository.Get(id);
            regionRepository.Delete(region);
        }
    }
}
